package com.ebelter.bodyfatscale.moudules.update;

import android.app.Service;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.support.v4.content.FileProvider;
import android.text.TextUtils;

import com.ebelter.bodyfatscale.moudules.https.NetUtils;
import com.ebelter.btlibrary.util.ULog;
import com.lzy.okgo.callback.FileCallback;

import java.io.File;

import okhttp3.Call;
import okhttp3.Response;

import static com.ebelter.bodyfatscale.moudules.https.HttpsUrl.UpdateBaseUri;


public class UpdateService extends Service {
    public static final String TAG="UpdateService";
    public static boolean isDownLoading=false;
    public static final String DownloadSer="DownloadPath";


    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        if (!isDownLoading){
            UpdateVersionBean updateVersionBean = (UpdateVersionBean) intent.getSerializableExtra(DownloadSer);

            if (updateVersionBean==null){
                return super.onStartCommand(intent, flags, startId);
            }else {
                ULog.i(TAG,"----onStartCommand-"+updateVersionBean.toString());
                String downloadPath=UpdateBaseUri+updateVersionBean.getFileName();
                //http://o.ebelter.com/apk_update/scal_apk/scaleFat_v1.0.17.apk
                NetUtils.getInstance().getFileDownLoad(this, downloadPath, new FileCallback() {
                    @Override
                    public void onSuccess(File file, Call call, Response response) {
                        isDownLoading=false;
                        if (file!=null&&file.getAbsolutePath().endsWith(".apk")){
                            install(file.getAbsolutePath());
                            ULog.i(TAG,"----下载完成---"+file.getAbsolutePath());
                        }


                    }
                    @Override
                    public void downloadProgress(long currentSize, long totalSize, float progress, long networkSpeed) {
                        super.downloadProgress(currentSize, totalSize, progress, networkSpeed);
                        isDownLoading=true;
                        ULog.i(TAG,"----下载中---currentSize="+currentSize+"--totalSize="+totalSize+"--progress="+progress+"--networkSpeed="+networkSpeed);
                    }

                    @Override
                    public void onError(Call call, Response response, Exception e) {
                        super.onError(call, response, e);
                        isDownLoading=false;
                        ULog.i(TAG,"----下载出错---");
                    }
                });
            }
        }


        return super.onStartCommand(intent, flags, startId);
    }




    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    private void install(String filePath) {
        ULog.i(TAG, "开始执行安装: " + filePath);
        File apkFile = new File(filePath);
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            ULog.i(TAG, "版本大于 N ，开始使用 fileProvider 进行安装");
            intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            Uri contentUri = FileProvider.getUriForFile(
                    this
                    , "com.ebelter2.bodyfatscale2.fileprovider"
                    , apkFile);
            intent.setDataAndType(contentUri, "application/vnd.android.package-archive");
        } else {
            ULog.i(TAG, "正常进行安装");
            intent.setDataAndType(Uri.fromFile(apkFile), "application/vnd.android.package-archive");
        }
        startActivity(intent);
    }

}
